<template>
  <div>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
        <!-- 搜索 -->
        <el-input placeholder="请输入内容" v-model="queryinfo.query" class="input-with-select" style="width:400px;" @input="getUser">
            <el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
        </el-input>
        <!-- 添加按钮 -->
        <el-button type="primary" style="margin-left:20px;" @click="dialogFormVisible  = true">添加用户</el-button>
        <!-- 添加弹出框 -->
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible ">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                <el-input v-model="ruleForm.mobile"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
                <el-button type="primary" @click="add(ruleForm)">确定</el-button>
              </el-form-item>
            </el-form>
        </el-dialog>


        <!-- 表格 -->
        <el-table
         :data="tableData"
         border
         style="width: 100%">
         <el-table-column
             type="index"
             label="#">
         </el-table-column>
         <el-table-column
             prop="username"
             label="姓名">
         </el-table-column>
         <el-table-column
             prop="email"
             label="邮箱">
         </el-table-column>
         <el-table-column
             prop="mobile"
             label="电话">
         </el-table-column>
         <el-table-column
             prop="role_name"
             label="角色">
         </el-table-column>
         <el-table-column
             prop="mg_state"
             label="状态">
             <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="change(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
             </template>
         </el-table-column>
         <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button
                type="primary"
                icon="el-icon-edit" 
                size="mini"
                @click="eEdit(scope.row.id)"></el-button>
                <el-button
                type="warning" 
                icon="el-icon-star-off"
                size="mini"
                @click="role(scope.row)"></el-button>
                <el-button
                size="mini"
                type="danger" 
                icon="el-icon-delete"
                @click="del(scope.row.id)"></el-button>
            </template>
         </el-table-column>
        </el-table>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑用户" :visible.sync="dialogFormVisible1 ">
            <el-form :model="ruleForm1" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm1.username" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm1.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                <el-input v-model="ruleForm1.mobile"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
                <el-button type="primary" @click="editup('ruleForm')">确定</el-button>
              </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 角色弹出框 -->
        <el-dialog title="分配角色" :visible.sync="dialogFormVisible2 ">
          <p>当前用户：{{content.username}}</p>
          <p>当前角色：{{content.role_name}}</p>
          <el-dropdown>
            当前新角色：
              <el-select v-model="value" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-dropdown>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="Roleup()">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 分页 -->
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryinfo.pagenum"
            :page-sizes="[1, 3, 5, 10]"
            :page-size="queryinfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {getUsersApi,addUsersApi,delUsersApi,changeUsersApi,eEditUsersApi,eEditupUsersApi,RoleListUsersApi,RoleupUsersApi} from  '../../http/api'
export default {
    data() {
      const checkmobile = (rule,value,callback)=>{
        const reg = /^1[3568]\d{9}$/
        if(!reg.test(value)){
          return callback(
            new Error('您的手机格式不正确,手机格式是：13xxxxxxxxx')
          )
        }
        callback()
      }
        return {
          tableData:[], //表格数据
          //分页数据
          queryinfo:{
            query:'',
            pagenum:1,
            pagesize:3,
          },
          total:0,
          // 添加用户弹框
          dialogFormVisible : false,
          // 编辑用户弹框
          dialogFormVisible1:false,
          // 角色用户弹框
          dialogFormVisible2:false,
          // 添加用户表单
          ruleForm: {
            username: '',
            password: '',
            email: '',
            mobile: '',
          },
          ruleForm1:{},
          // 角色
          content:{},
          // 角色列表
          options:{},
          // 角色列表的id
          value:'',
          // 添加用户表单验证
          rules: {
            username: [
              { required: true, message: '请输入用户名', trigger: 'blur' },
              { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
            ],
            password: [
              { required: true, message: '请输入密码', trigger: 'blur' },
              { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
            ],
            email:[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            mobile:[
               { required: true, message: '请输入电话', trigger: 'blur' },
              { validator:checkmobile, message: '请输入正确的电话', trigger: ['blur', 'change'] }
            ]
          }
        }
    },
    created(){
        this.getUser()
    },
    methods: {
      // 渲染
        async getUser(){
          const res = await getUsersApi(this.queryinfo)
          console.log(res);
          this.tableData = res.users
          this.total = res.total
        },
        // 分页
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.queryinfo.pagesize = val
            this.getUser()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.queryinfo.pagenum = val
            this.getUser()
        },
        // 添加用户
        add() {
          this.$refs.ruleForm.validate(async valid => {
            if (!valid) {
              return false
            }
            const res = await addUsersApi(this.ruleForm)
            console.log(res);
            this.dialogFormVisible = false
            this.getUser()
          });
        },
        // 添加重置
        resetForm(formName) {
          this.$refs[formName].resetFields();
        },
        // 删除用户
        del(id){
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delUsersApi(id).then(res=>{
              console.log(res);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getUser()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
        },
        // 修改状态
        async change(row){
          const {id,mg_state} = row
          await changeUsersApi(id,mg_state)
          this.getUser()
        },
        // 编辑的数据回填
        async eEdit(id){
          this.dialogFormVisible1 = true
          const res = await eEditUsersApi(id)
          console.log(res);
          this.ruleForm1 = res
        },
        // 修改编辑的数据
        editup(id){
          this.$refs.ruleForm.validate(async valid => {
            if (!valid) {
              return false
            }
            const {id,email,mobile } = this.ruleForm1
            const res = await eEditupUsersApi(id,{email:email, mobile:mobile})
            console.log(res);
            this.dialogFormVisible1 = false
            this.getUser()
          });
        },
        // 分配角色列表
        async role(row){
          this.dialogFormVisible2 = true
          const {id,role_name,username} = row
          this.content = {id,role_name,username}
          // console.log(this.content);
          const res = await RoleListUsersApi()
          // console.log(res);
          this.options = res
        },
        async Roleup(){
          const res = await RoleupUsersApi(this.content.id,this.value)
          console.log(res);
          this.dialogFormVisible2 = false
          this.getUser()
        },
    },
} 
</script>

<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .el-card{
    margin: 20px;
  }
  .el-table{
    margin: 15px 0;
  }
</style>